const webpack = require("webpack");
const glob = require("glob");
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require("copy-webpack-plugin");

const isDev = process.env.NODE_ENV === "development";
const htmlPluginArray =[]
function getEntry() {
  const entry = {};
  //读取src目录所有page入口
  glob.sync('./src/**/index.js')
    .forEach(function (filePath) {
      var name = filePath.match(/\/src\/(.+)\/index.js/);
      name = name ? name[1] : "index"; //
      entry[name] = filePath;
      htmlPluginArray.push(new HtmlWebpackPlugin({
        filename: path.join(__dirname, `./dist/${name}.html`),
        template: path.join(__dirname, `./src/${name}/index.ejs`),
        chunks: [name],
        minify: {
          // collapseWhitespace: !isDev
        }
      }))
    });
  return entry;
};
const CONFIG = {
  mode: isDev ? 'development' : "production",
  devtool: isDev ? "cheap-module-eval-source-map" : undefined,
  // 多入口
  entry: getEntry(),
  output: {
    // publicPath: './',
    filename: `js/[name].[${isDev ? "hash:8" : "contentHash:8"}].js`,
    chunkFilename: `js/[name]_[${isDev ? "hash:8" : "contentHash:8"}].min.js`,
    path: path.join(__dirname, "./dist"),
  },
  devServer: {
    port: 8888,
    host: "localhost",
    clientLogLevel: "warning",
    contentBase: path.join(__dirname, 'dist'),
    historyApiFallback: true,
  },
  resolve: {
    modules: [path.resolve(__dirname, 'node_modules')],
    extensions: [".js", ".less"],
    alias: {
      common: path.resolve(__dirname, "./src/common/"),
      '@src': path.join(__dirname, "./src")
    }
  },
  module: {
    rules: [{
      test: /\.(le|c)ss$/,
      use: [
        MiniCssExtractPlugin.loader,
        'css-loader',
        {
          loader: "postcss-loader",
          options: {
            plugins: [
              require("autoprefixer")
            ]
          }
        },
        'less-loader'
      ]
    },
    {
      test: /\.js$/, //js文件加载器
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env']
        }
      }
    },
    {
      test: /\.html$/,
      use: [{
        loader: 'html-loader',
        options: {
          interpolate: true,
          minimize: false
        }
      }]
    }, {
      test: /\.ejs/,
      use: ['ejs-loader'],
    }
    ]
  },
  optimization: {
    splitChunks: {
      chunks: "all",
      cacheGroups: {
        vendor: {  // 抽离第三方插件
          test: /[\\/]node_modules[\\/]/,     // 指定是node_modules下的第三方包
          // name: "jquery",
          priority: 10,                       // 抽取优先级
          minChunks: 2 //在分割之前，这个代码块最小应该被引用的次数
        },
        /* styles: {
          name: 'base',
          test: /\.(less|css)$/,
          minChunks: 2,
          reuseExistingChunk: true,
          enforce: true
        } */
        commons: {
          test: /[\\/]src[\\/]common[\\/]/,
          name: 'commons',
          // minSize: 30000,
          minChunks: 2,
          // chunks: 'initial',
          priority: 1,
          reuseExistingChunk: true // 这个配置允许我们使用已经存在的代码块
        }
      }
    }
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: "jquery"
    }),
    new MiniCssExtractPlugin({
      filename: 'css/[name].[contenthash:8].css',
      chunkFilename: 'css/[name].[contenthash:8].css',
    }),
    new CopyWebpackPlugin({
      patterns: [{
        from: path.resolve(__dirname, "./static"),
        to: path.resolve(__dirname, "./dist/static"),
        toType: "dir"
      }]
    }),
    ...htmlPluginArray
  ]
}
if (!isDev) {
  CONFIG.plugins.unshift(new CleanWebpackPlugin());
}
module.exports = CONFIG